﻿using UnityEngine;
using UnityEngine.Rendering;
/// <summary>
/// jave.lin 2020.04.15 测试 CommandBuffer.SetViewProjectionMatrices 与测试 CommandBuffer.DrawMesh 配合使用设置Unity内置变换矩阵 ;
/// 没什么卵用；测试多个相机绘制而已；
/// </summary>
public class CommandBufferViewProjTester : MonoBehaviour
{
    public Camera cam;                  // 用于观察的Camera
    public Camera hidenCam;             // 用于类似RT渲染用的Camera，看看能否指定M,V,P各个矩阵
    public Material mat;                // 绘制用的材质
    public GameObject cubeHolder;       // Cube的LocalToWorldMatrix的挂点对象
    public bool withCubeHolder = true;  // 是否使用Cube挂点
    public bool setViewProj = true;     // 是否设置CommandBuffer.SetViewProjectionMatrices

    private CommandBuffer cmdBuff;
    private Mesh mesh;

    private void Start()
    {
        cmdBuff = new CommandBuffer();
        cmdBuff.name = "[Testing CmdBuff Set V P & DrawMesh]";

        var cubeGO = GameObject.CreatePrimitive(PrimitiveType.Cube);
        mesh = cubeGO.GetComponent<MeshFilter>().mesh;
        Destroy(cubeGO);
    }

    private void OnRenderObject()
    {
        cmdBuff.Clear();
        if (setViewProj)
        {
            cmdBuff.SetViewProjectionMatrices(hidenCam.worldToCameraMatrix, GL.GetGPUProjectionMatrix(hidenCam.projectionMatrix, false));
        }
        if (withCubeHolder)
        { // 所以DrawMesh的第二个Matrix4x4就是L2W的矩阵
            // 从CommandBuffer的API可以看到各个DrawXXX()中的Matrix的注释都是一样的，说明都是LocalToWorldMatrix。
            cmdBuff.DrawMesh(mesh, cubeHolder.transform.localToWorldMatrix, mat);
        }
        else
        {
            cmdBuff.DrawMesh(mesh, Matrix4x4.identity, mat);
        }

        Graphics.ExecuteCommandBuffer(cmdBuff);
    }
}